<?php

namespace app\agent\controller;

use app\models\{Order as Orders, Region, Agent as Agents, Riderlist, RiderStreet};
use think\Db;
use think\facade\Debug;
use think\Facade\Config as Configs;
use app\facade\Redis;


class Main extends Base
{

    public function welcome()
    {

        if ($this->request->isAjax()) {
            $model = new Orders();
            $post = input();
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['id|ordersn|name|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['created'])) {
                $start = $post['created']['startime'] ?? date('Y-m-d H:i:s');
                $end = $post['created']['endtime'] ?? date('Y-m-d H:i:s');
                $where[] = ['created', 'between', [$start, $end]];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['payment'])) {
                $where[] = ['payment', '=', $post['payment']];
            }
            if (!empty($post['riderid'])) {
                $where[] = ['orderid', '=', $post['riderid']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            if (empty($post['chaxun'])) {
                return json(['code' => 200, 'msg' => '获取成功', 'data' => []]);
            }
            $arr = [
                'count' => $model->where($where)->count(), //订单量
                'ptotal' => $model->where($where)->sum('ptotal'), //实际价格
                'total' => $model->where($where)->sum('total'), //累计价格
                'dicttotal' => $model->where($where)->sum('dicttotal'), //折扣价格
                'cmoney' => $model->where($where)->sum('cmoney'), //优惠券价格
            ];
            $arr['dptotal'] = floor(($arr['ptotal'] - $arr['dicttotal']) * 100) / 100; //折扣优惠
            $list[] = $arr;
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list]);
        } else {
            $name = 'getagentweclome_' . $this->request->agent['id'];
            $data = Redis::get($name);
            $list = [];
            if ($data) {
                $list = unserialize($data);
            } else {
                //昨日凌晨时间
                $ystdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', time() - 86400)));
                //今日凌晨时间
                $tstdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', time())));
                $tetdate = date('Y-m-d H:i:s');
                $where[] = ['agentid', '=', $this->request->agent['id']];
                $data = [
                    //交易额
                    'alltotal' => [
                        'money' => (new Orders())->where($where)->where(['status' => [2, 3, 4]])->sum('total'), //营业额
                        'ytotal' => (new Orders())->where($where)->whereBetweenTime('created', $ystdate, $tstdate)->where(['status' => [2, 3, 4]])->sum('total'), //周同比
                        'ttotal' => (new Orders())->where($where)->whereBetweenTime('created', $tstdate, $tetdate)->where(['status' => [2, 3, 4]])->sum('total') // 日销售额
                    ],
                    //支付金额
                    'palltotal' => [
                        'money' => (new Orders())->where($where)->where(['status' => [2, 3, 4], 'payment' => [2]])->sum('total'), //营业额
                        'money1' => (new Orders())->where($where)->where(['status' => [2, 3, 4], 'payment' => [1]])->sum('total'), //营业额
                        'ttotal' => (new Orders())->where($where)->whereBetweenTime('created', $tstdate, $tetdate)->where(['status' => [2, 3, 4], 'payment' => [2]])->sum('total')
                    ],
                    //下单量
                    'ordercount' => [
                        'count' => (new Orders())->where($where)->where(['status' => [2, 3, 4]])->count(), //营业额
                        'ycount' => (new Orders())->where($where)->whereBetweenTime('created', $ystdate, $tstdate)->where(['status' => [2, 3, 4]])->count(), //周同比
                        'tcount' => (new Orders())->where($where)->whereBetweenTime('created', $tstdate, $tetdate)->where(['status' => [2, 3, 4]])->count() // 日销售额
                    ],
                    //待服务订单量
                    'orderd' => [
                        'count' => (new Orders())->where($where)->where(['status' => [2]])->count(), //营业额
                        'total' => (new Orders())->where($where)->where(['status' => [2]])->sum('total'), //周同比
                        'ttotal' => (new Orders())->where($where)->whereBetweenTime('created', $tstdate, $tetdate)->where(['status' => [2]])->sum('total') // 日销售额
                    ]
                ];
                Redis::setex($name, 3600, serialize($data));
                $list = $data;
            }
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');

            //获取所有下级代理
            $agents =  (new Agents())->where('top', $this->request->agent['id'])->field('id,nickname')->select();
            //上个月起始时间
            $begin_time = date('Y-m-01 00:00:00', strtotime('-1 month'));
            //本月起始时间
            $begin_timeend = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y")));
            //本月末时间
            $end_timeing = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("t"), date("Y")));
            foreach ($agents as $agent) {
                $agent['order'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->count(); //统计累计完成订单量
                $agent['ptotal'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->sum('ptotal'); //统计累计完成订单金额（原价）
                //上个月订单计总
                $agent['orderend'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->whereBetweenTime('created', $begin_time, $begin_timeend)->count(); //统计累计完成订单量
                $agent['ptotalend'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->whereBetweenTime('created', $begin_time, $begin_timeend)->sum('ptotal'); //统计累计完成订单金额（原价）
                //本月统计
                $agent['ordereing'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->whereBetweenTime('created', $begin_timeend, $end_timeing)->count(); //统计累计完成订单量
                $agent['ptotaling'] = (new Orders())->where(['agentid' => $agent['id'], 'status' => [4]])->whereBetweenTime('created', $begin_timeend, $end_timeing)->sum('ptotal'); //统计累计完成订单金额（原价）
            }
            return view(null, [
                'data' => $list,
                'province' => (new Region())->where(['level' => 1])->select(),
                'rider' => (new Riderlist())->where(['id' => $riderid])->field('id,name,mobile')->select(),
                'agents' => $agents
            ]);
        }
    }

    public function index()
    {
        $agent = $this->request->agent;
        return view(null, [
            'agent' => $agent
        ]);
    }


    public function miss()
    {
        return view('404');
    }

    public function miss2()
    {
        return view('500');
    }
}
